package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.ApCollectionService;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private ApCollectionMapper apCollectionMapper;

    @Override
    public ResponseResult saveApCollection(CollectionBehaviorDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关注人不存在");
        }
        /*通过feign来调用 查询实体*/
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findApBehaviorEntry(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实体不存在");
        }

        /*判重一下*/
        List<ApCollection> collectionList = apCollectionMapper.selectList(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, apBehaviorEntry.getId())
                .eq(ApCollection::getArticleId, dto.getEntryId()).eq(ApCollection::getType, dto.getType()));

        /*判断是不是收藏*/
        if (dto.getOperation()==0){
            /*保存*/
            ApCollection apCollection = new ApCollection();
            if (collectionList.size()==0) {
                apCollection.setEntryId(apBehaviorEntry.getId());
                apCollection.setArticleId(dto.getEntryId());
                apCollection.setType(dto.getType());
                apCollection.setCollectionTime(new Date());
                apCollection.setPublishedTime(dto.getPublishedTime());
                this.save(apCollection);
            }
        }else {
            if (collectionList.size()==1) {
                ApCollection apCollection = collectionList.get(0);
                this.removeById(apCollection.getId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
